#include <iostream>
#include <sys/types.h>
#include <sys/socket.h>
#include <cerrno>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <string>
#include <cstdlib>
#include <cstring>
#include <cstdio>

void Usage(std::string proc)
{
    std::cout << "Usage: \n\t " << proc << "server_ip  "
              << "server_port" << std::endl;
}
int main(int argc, char *argv[])
{
    if (argc != 3)
    {
        Usage(argv[0]);
        return 0;
    }
    int sock = socket(AF_INET, SOCK_DGRAM, 0);
    if (sock < 0)
    {
        std::cerr << "sock create error:" << errno << std::endl;
        return 1;
    }
    sockaddr_in server;
    server.sin_family = AF_INET;
    server.sin_port = htons(atoi(argv[2]));
    server.sin_addr.s_addr = inet_addr(argv[1]);
    while (1)
    {
        std::cout << "MYSHELL $ ";
        char line[1024];
        fgets(line, sizeof(line), stdin);

        sendto(sock, line, strlen(line), 0, (sockaddr *)&server, sizeof(server));
        sockaddr_in tmp;
        socklen_t len = sizeof(tmp);
        char buffer[1024];
        ssize_t cnt = recvfrom(sock, buffer, sizeof(buffer), 0, (sockaddr *)&tmp, &len);
        if (cnt > 0)
        {
            buffer[cnt] = 0;
            std::cout << buffer << std::endl;
        }
    }
    return 0;
}